﻿using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using BlankMvc.Dao.Entities.Impl;
using BlankMvc.Dao.Repository.Interface;
using BlankMvc.Services.Interfaces;
using BlankMvc.Types;

namespace BlankMvc.Services.Impl {
	public class UserService : IUserService {

		private const string identityprovider = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider";

		public IUserRepository UserRepository { get; set; }

		public User ValidateUser(string login, string password) {
			return UserRepository.FindAuthorise(login, GetPasswordHash(password));
		}

		public User UpdateUserPassword(UserEditPassword usr) {
			User current = ValidateUser(usr.Login, usr.Password);
			current.PasswordHash = GetPasswordHash(usr.NewPassword);
			UserRepository.Update(current);
			return current;
		}

		public ClaimsIdentity[] CreateIdentity(User user, string applicationCookie) {
			List<Claim> claims = new List<Claim> {
				new Claim(ClaimTypes.Role, ""),
				new Claim(ClaimTypes.Name, "Иван"),
				new Claim(identityprovider, "BlankMvc"),
				new Claim(ClaimTypes.NameIdentifier, "BD01B046-AB8B-4BA6-81AC-042CBD9BA747"),
				new Claim(ClaimTypes.Email, "brockallen@gmail.com")
			};
			var id = new ClaimsIdentity(claims, applicationCookie);

			return new[] { id };
		}

		public string GetPasswordHash(string password) {
			string hsh = GenerateHash(password);
			return GenerateHash(hsh.Substring(0, hsh.Length - 5));
		}

		private static string GenerateHash(string input) {
			byte[] data = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input));
			StringBuilder bld = new StringBuilder();
			foreach (byte dat in data)
				bld.Append(dat.ToString("x2"));
			return bld.ToString();
		}

	}
}
